package com.xcm.controller;

import com.alibaba.fastjson.JSONObject;
import com.xcm.constant.BaseConstant;
import com.xcm.constant.SysRoleConstants;
import com.xcm.exception.ServiceException;
import com.xcm.model.SysRole;
import com.xcm.model.response.JsonResponseBuilder;
import com.xcm.model.vo.SysRoleVo;
import com.xcm.page.PageInfo;
import com.xcm.service.SysRoleService;
import com.xcm.util.CollectionsUtil;
import com.xcm.validator.SysRoleValidator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 角色
 *
 * @author linqiang
 * @date 2018-04-13 9:15
 */
@Controller
@RequestMapping(value = "/sysRole")
public class SysRoleController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(SysRoleController.class);
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 新增角色(同时绑定权限)
     *
     * @param sysRoleJson  新增的角色JSON串
     * @param authorityIds 权限id（多个以英文逗号隔开）
     * @return
     */
    @RequestMapping(value = "/saveSysRole")
    @ResponseBody
    public Object saveSysRole(String sysRoleJson, String authorityIds) {
        try {
            if (StringUtils.isBlank(sysRoleJson)) {
                return JsonResponseBuilder.buildSuccess(SysRoleConstants.VALIDATE_NO_SYS_ROLE);
            }
            JSONObject object = JSONObject.parseObject(sysRoleJson);
            SysRole sysRole = JSONObject.toJavaObject(object, SysRole.class);
            //参数校验
            String formValidateResult = SysRoleValidator.validateSysRole(sysRole);
            if (StringUtils.isNotBlank(formValidateResult)) {
                return JsonResponseBuilder.buildFail(formValidateResult);
            }
            int effectRow = sysRoleService.save(sysRole, authorityIds);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysRoleConstants.SAVE_SUCCESS);
            }
        } catch (Exception e) {
            logger.error("SysRoleController saveSysRole 新增角色失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysRoleConstants.SAVE_FAIL);
    }


    /**
     * 修改角色(同时绑定权限)
     *
     * @param sysRoleJson  修改的角色JSON串
     * @param authorityIds 权限id（多个以英文逗号隔开）
     * @return
     */
    @RequestMapping(value = "/updateSysRole")
    @ResponseBody
    public Object updateSysRole(String sysRoleJson, String authorityIds) {
        try {
            if (StringUtils.isBlank(sysRoleJson)) {
                return JsonResponseBuilder.buildSuccess(SysRoleConstants.VALIDATE_NO_SYS_ROLE);
            }
            JSONObject object = JSONObject.parseObject(sysRoleJson);
            SysRoleVo sysRoleVo = JSONObject.toJavaObject(object, SysRoleVo.class);
            SysRole sysRole = new SysRole();
            BeanUtils.copyProperties(sysRoleVo, sysRole);
            //表单必要属性验证
            String formValidateResult = SysRoleValidator.validateSysRole(sysRole);
            if (StringUtils.isNotBlank(formValidateResult)) {
                return JsonResponseBuilder.buildFail(formValidateResult);
            }
            int effectRow = sysRoleService.update(sysRole, authorityIds);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysRoleConstants.UPDATE_SUCCESS);
            }
        } catch (Exception e) {
            logger.error("SysRoleController updateSysRole 修改角色失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysRoleConstants.UPDATE_FAIL);
    }

    /**
     * 删除角色
     *
     * @param roleId 删除的角色id
     * @return
     */
    @RequestMapping(value = "/deleteSysRole")
    @ResponseBody
    public Object deleteSysRole(Integer roleId) {
        try {
            if (null == roleId) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
            }
            int effectRow = sysRoleService.deleteById(roleId);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysRoleConstants.DELETE_SUCCESS);
            }
        } catch (ServiceException e) {
            logger.error("SysRoleController deleteSysRole 删除角色失败：" + e.getMessage());
            return JsonResponseBuilder.buildFail(e.getMessage());
        } catch (Exception e) {
            logger.error("SysRoleController deleteSysRole 删除角色失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysRoleConstants.DELETE_FAIL);
    }

    /**
     * 批量删除角色
     *
     * @param roleIds 批量删除的角色id（多个以英文逗号隔开）
     * @return
     */
    @RequestMapping(value = "/batchDeleteSysRole")
    @ResponseBody
    public Object batchDeleteSysRole(String roleIds) {
        try {
            if (null == roleIds) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
            }
            List<String> roleIdListStr = Arrays.asList(roleIds.split(BaseConstant.COMMA_EN));
            if (CollectionUtils.isEmpty(roleIdListStr)) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
            }
            List<Integer> roleIdList = CollectionsUtil.listStrngToInteger(roleIdListStr);
            if (roleIdList.contains(BaseConstant.SUPER_ADMIN_ROLE_ID)) {
                return JsonResponseBuilder.buildFail(SysRoleConstants.DELETE_FAIL_SUPER_ROLE_CANNOT_DELETE);
            }
            int effectRow = sysRoleService.batchDeleteRole(roleIdList);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysRoleConstants.DELETE_SUCCESS);
            }
        } catch (ServiceException e) {
            logger.error("SysRoleController batchDeleteSysRole 批量删除角色失败：" + e.getMessage());
            return JsonResponseBuilder.buildFail(e.getMessage());
        } catch (Exception e) {
            logger.error("SysRoleController batchDeleteSysRole 批量删除角色失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysRoleConstants.DELETE_FAIL);
    }

    /**
     * 根据id查询
     *
     * @param roleId 角色id
     * @return
     */
    @RequestMapping(value = "/getById")
    @ResponseBody
    public Object getById(Integer roleId) {
        if (null == roleId) {
            return BaseConstant.MSG_PARAM_ERROR;
        }
        try {
            SysRoleVo sysRoleVo = sysRoleService.getByIdVo(roleId);
            if (null == sysRoleVo) {
                return JsonResponseBuilder.buildFail(SysRoleConstants.ROLE_NOT_EXITS);
            }
            return JsonResponseBuilder.buildSuccess(sysRoleVo);
        } catch (Exception e) {
            logger.error("SysUserController getById 根据id查询用户失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysRoleConstants.GET_FAIL);
    }

    /**
     * 给角色添加用户(可同时添加多个用户)
     *
     * @param roleId  角色id
     * @param userIds 用户id(多个以英文逗号隔开)
     * @return
     */
    @RequestMapping(value = "/saveUserForRole")
    @ResponseBody
    public Object saveUserForRole(Integer roleId, String userIds) {
        try {
            if (null == roleId) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
            }
            sysRoleService.saveUserForRole(roleId, userIds);
        } catch (Exception e) {
            logger.error("SysRoleController saveUserForRole 给角色添加用户失败：" + e.getMessage());
            return JsonResponseBuilder.buildFail(SysRoleConstants.SAVE_USER_FOR_ROLE_FAIL);
        }
        return JsonResponseBuilder.buildSuccess(SysRoleConstants.SAVE_USER_FOR_ROLE_SUCCESS);
    }

    /**
     * 角色集合查询
     *
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list() {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            List<SysRole> sysRoleList = sysRoleService.list(paramMap);
            if (CollectionUtils.isEmpty(sysRoleList)) {
                sysRoleList = new ArrayList<>();
            }
            return JsonResponseBuilder.buildSuccess(sysRoleList);
        } catch (Exception e) {
            logger.error("SysRoleController list 角色集合查询失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(BaseConstant.QUERY_FAIL);
    }

    /**
     * 角色分页查询
     *
     * @param pageNum  第几页
     * @param pageSize 每页几条
     * @param roleName 角色名称(模糊匹配)
     * @return
     */
    @RequestMapping(value = "/listPage")
    @ResponseBody
    public Object listPage(Integer pageNum, Integer pageSize, String roleName) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            if (StringUtils.isNotBlank(roleName)) {
                paramMap.put("roleName", roleName);
            }
            PageInfo<SysRole> sysRolePageInfo = sysRoleService.listPage(paramMap,
                    pageNum == null ? super.pageNum : pageNum,
                    pageSize == null ? super.pageSize : pageSize);
            return JsonResponseBuilder.buildSuccess(sysRolePageInfo);
        } catch (Exception e) {
            logger.error("SysRoleController listPage 角色分页查询失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(BaseConstant.QUERY_FAIL);
    }


    /**
     * 批量启用角色
     *
     * @param roleIds 批量启用的角色id（多个以英文逗号隔开）
     * @return
     */
    @RequestMapping(value = "/batchEnableSysRole")
    @ResponseBody
    public Object batchEnableSysRole(String roleIds) {
        try {
            if (null == roleIds) {
                return JsonResponseBuilder.buildFail(SysRoleConstants.ENABLE_FAIL_NO_SELECT);
            }
            List<String> roleIdListStr = Arrays.asList(roleIds.split(BaseConstant.COMMA_EN));
            if (CollectionUtils.isEmpty(roleIdListStr)) {
                return JsonResponseBuilder.buildFail(SysRoleConstants.ENABLE_FAIL_NO_SELECT);
            }
            List<Integer> roleIdList = CollectionsUtil.listStrngToInteger(roleIdListStr);
            int effectRow = sysRoleService.batchEnableOrDisableRole(roleIdList, SysRoleConstants.ABLE_ENABLE);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysRoleConstants.ENABLE_SUCCESS);
            }
        } catch (Exception e) {
            logger.error("SysRoleController batchDeleteSysRole 批量删除角色失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysRoleConstants.ENABLE_FAIL);
    }


    /**
     * 批量停用角色
     *
     * @param roleIds 批量停用的角色id（多个以英文逗号隔开）
     * @return
     */
    @RequestMapping(value = "/batchDisableSysRole")
    @ResponseBody
    public Object batchDisableSysRole(String roleIds) {
        try {
            if (null == roleIds) {
                return JsonResponseBuilder.buildFail(SysRoleConstants.DISABLE_FAIL_NO_SELECT);
            }
            List<String> roleIdListStr = Arrays.asList(roleIds.split(BaseConstant.COMMA_EN));
            if (CollectionUtils.isEmpty(roleIdListStr)) {
                return JsonResponseBuilder.buildFail(SysRoleConstants.DISABLE_FAIL_NO_SELECT);
            }
            List<Integer> roleIdList = CollectionsUtil.listStrngToInteger(roleIdListStr);
            if (roleIdList.contains(BaseConstant.SUPER_ADMIN_ROLE_ID)) {
                return JsonResponseBuilder.buildFail(SysRoleConstants.DISABLE_FAIL_HAS_SUPER_ROLE);
            }
            int effectRow = sysRoleService.batchEnableOrDisableRole(roleIdList, SysRoleConstants.ABLE_DISABLE);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysRoleConstants.DISABLE_SUCCESS);
            }
        } catch (Exception e) {
            logger.error("SysRoleController batchDisableSysRole 批量停用角色失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysRoleConstants.DISABLE_FAIL);
    }
}
